package org.jeecg.common.util;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import io.swagger.util.Json;
import lombok.Data;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;

import java.lang.reflect.Type;
import java.util.List;

/**
 * 企业微信工具类
 */
@Component
public class QiWeiUtil {
    public RedisUtil getRedisUtil() {
        return redisUtil;
    }

    public void setRedisUtil(RedisUtil redisUtil) {
        this.redisUtil = redisUtil;
    }

    public String getCorpid() {
        return corpid;
    }

    public void setCorpid(String corpid) {
        this.corpid = corpid;
    }

    public String getAppsecret() {
        return appsecret;
    }

    public void setAppsecret(String appsecret) {
        this.appsecret = appsecret;
    }

    public String getAgentid() {
        return agentid;
    }

    public void setAgentid(String agentid) {
        this.agentid = agentid;
    }

    public void setAccessToken(String accessToken) {
        this.accessToken = accessToken;
    }

    @Autowired
    private RedisUtil redisUtil;
    /**企业ID*/
    @Value("${justauth.type.WECHAT_ENTERPRISE.client-id}")
    private String corpid;

    /**应用ID*/
    @Value("${justauth.type.WECHAT_ENTERPRISE.client-secret}")
    private String appsecret;

    @Value("${justauth.type.WECHAT_ENTERPRISE.agent-id}")
    private String agentid;

    private String accessToken ;


    /**1. 得到access_token
     * https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=ID&corpsecret=SECRET

     * @return
     */
    private void getAccessToken() {

         if(redisUtil.hasKey("qiwei_access_token")){
             accessToken = redisUtil.get("qiwei_access_token").toString();
         }
         else{
             JSONObject jsonObject = RestUtil.get("https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=" + corpid + "&corpsecret=" + appsecret);
             Assert.isTrue(jsonObject.getInteger("errcode") == 0, "企业微信获取access_token失败"
                +jsonObject.getString("errmsg"));

            accessToken = jsonObject.getString("access_token");
            redisUtil.set("qiwei_access_token",accessToken,
                jsonObject.getLong("expires_in")-100);
         }

    }

    /**2. 发送消息
     * https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=ACCESS_TOKEN
     * @msgtype  text|image|voice|video|file|news
     * @param content 消息内容 {} 字符串对象
     * @param touser 用户ID  指定 @all 表示发送给所有人
     */
    public  String sendMessage(String touser, String msgtype, String agentid,String content)  {
        getAccessToken();
        Assert.isTrue(accessToken != null, "企业微信获取access_token失败");

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("touser", touser);
        jsonObject.put("msgtype", msgtype);
        jsonObject.put("agentid", agentid);
        JSONObject jsonContent = JSONObject.parseObject(content);
        jsonObject.put(msgtype, jsonContent);

        JSONObject post = RestUtil.post("https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=" + accessToken, jsonObject);

        Assert.isTrue(post.getInteger("errcode") == 0, "企业微信发送消息失败:"
                +post.getString("errmsg"));
        return post.getString("msgid");
    }

    /**
     * 3. 获取审批数据列表
     * https://qyapi.weixin.qq.com/cgi-bin/oa/getapprovalinfo?access_token=ACCESS_TOKEN
     */
    public  List<String> getApprovalData(String starttime, String endtime,
                                             Integer cursor, Integer size, List<JSONObject> filters) {
        getAccessToken();
        Assert.isTrue(accessToken != null, "企业微信获取access_token失败");
        JSONObject jsonObject =new JSONObject();
        jsonObject.put("starttime", starttime);
        jsonObject.put("endtime", endtime);
        jsonObject.put("cursor", cursor);
        jsonObject.put("size", size);
        jsonObject.put("filters", filters);

        JSONObject jsonObject2 = RestUtil.post("https://qyapi.weixin.qq.com/cgi-bin/oa/getapprovalinfo?access_token="
                + accessToken,jsonObject );

        Assert.isTrue(jsonObject2.getInteger("errcode") == 0, "企业微信获取审批数据失败:"
                +jsonObject2.getString("errmsg"));
        return JSONObject.parseArray(jsonObject2.getString("sp_no_list"),String.class);

    }

    /**4. 获取审批详情
     * https://qyapi.weixin.qq.com/cgi-bin/oa/getapprovaldetail?access_token=ACCESS_TOKEN
     * @accessToken 企业微信获取的access_token
     * @sp_no 审批单号
     */
    public JSONObject getApprovalDetail( String sp_no) {
        getAccessToken();
        Assert.isTrue(accessToken != null, "企业微信获取access_token失败");

        Assert.isTrue(sp_no != null, "sp_no不存在");
        Assert.isTrue(sp_no.length() > 0, "sp_no不能为空");

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("sp_no", sp_no);

        JSONObject jsonObject2 = RestUtil.post("https://qyapi.weixin.qq.com/cgi-bin/oa/getapprovaldetail?access_token="
                + accessToken ,jsonObject);

        Assert.isTrue(jsonObject2.getInteger("errcode") == 0, "企业微信获取审批详情失败:"
                +jsonObject.getString("errmsg"));

        return jsonObject2;
    }

    /**5. 获取部门列表
     * https://qyapi.weixin.qq.com/cgi-bin/department/list?access_token=ACCESS_TOKEN&id=1
     * @accessToken 企业微信获取的access_token
     * @id 部门id
     * return List<JSONObject> 部门列表
     */
    public  List<JSONObject> getDepartmentList( Integer id) {
        getAccessToken();
        Assert.isTrue(accessToken != null, "企业微信获取access_token失败");
        Assert.isTrue(id != null, "部门id不存在");

        JSONObject jsonObject = RestUtil.get("https://qyapi.weixin.qq.com/cgi-bin/department/list?access_token="
                + accessToken + "&id=" + id);

        Assert.isTrue(jsonObject.getInteger("errcode") == 0, "企业微信获取部门列表失败:"
                +jsonObject.getString("errmsg"));
        return JSONObject.parseArray(jsonObject.getString("department"),JSONObject.class);
    }

    /**6. 获取部门成员列表
     * https://qyapi.weixin.qq.com/cgi-bin/user/simplelist?access_token=ACCESS_TOKEN&department_id=1
     */
    public  List<JSONObject> getDepartmentUsersimplelist(Integer department_id) {
        getAccessToken();
        Assert.isTrue(accessToken != null, "企业微信获取access_token失败");
        Assert.isTrue(department_id != null, "部门id不存在");

        JSONObject jsonObject = RestUtil.get("https://qyapi.weixin.qq.com/cgi-bin/user/simplelist?access_token="
                + accessToken + "&department_id=" + department_id );

        Assert.isTrue(jsonObject.getInteger("errcode") == 0, "企业微信获取部门成员列表失败:"
                +jsonObject.getString("errmsg"));
        return JSONObject.parseArray(jsonObject.getString("userlist"),JSONObject.class);
    }
    /**7. 获取部门成员详情
     * https://qyapi.weixin.qq.com/cgi-bin/user/list?access_token=ACCESS_TOKEN&department_id=1
     *
     */
    public  List<JSONObject> getDepartmentUserlist( Integer department_id) {
        getAccessToken();
        Assert.isTrue(accessToken != null, "企业微信获取access_token失败");
        Assert.isTrue(department_id != null, "部门id不存在");

        JSONObject jsonObject = RestUtil.get("https://qyapi.weixin.qq.com/cgi-bin/user/list?access_token="
                + accessToken + "&department_id=" + department_id );

        Assert.isTrue(jsonObject.getInteger("errcode") == 0, "企业微信获取部门成员详情失败:"
                +jsonObject.getString("errmsg"));
        return JSONObject.parseArray(jsonObject.getString("userlist"),JSONObject.class);
    }

    /** 8. 读取成员信息
     * https://qyapi.weixin.qq.com/cgi-bin/user/get?access_token=ACCESS_TOKEN&userid=zhangsan
     */
    public  JSONObject getUserInfo( String userid) {
        getAccessToken();
        Assert.isTrue(accessToken != null, "企业微信获取access_token失败");
        Assert.isTrue(userid != null, "userid不存在");

        JSONObject jsonObject = RestUtil.get("https://qyapi.weixin.qq.com/cgi-bin/user/get?access_token="
                + accessToken + "&userid=" + userid );

        Assert.isTrue(jsonObject.getInteger("errcode") == 0, "企业微信读取成员信息失败:"
                +jsonObject.getString("errmsg"));
        return jsonObject;
    }

    /** 10. 获取工号
     *
     * @param userid
     * @return 工号
     */
    public String GongHao(String userid){
        JSONObject userInfo= getUserInfo(userid);
        JSONObject extattr = userInfo.getJSONObject("extattr");
        JSONArray attrs = extattr.getJSONArray("attrs");
        for (int i = 0; i < attrs.size(); i++) {
            if (attrs.getJSONObject(i).getString("name").equals("工号")){
                return attrs.getJSONObject(i).getString("value");
            }
        }

        return null;

    }

    /** 9. 手机号获取userid
     * https://qyapi.weixin.qq.com/cgi-bin/user/getuserid?access_token=ACCESS_TOKEN&mobile=13800000000
     *
     */
    public  String getUserid(String mobile) {
        getAccessToken();
        Assert.isTrue(accessToken != null, "企业微信获取access_token失败");
        Assert.isTrue(mobile != null, "手机号不存在");

        JSONObject jsonObject1 = new JSONObject();
        jsonObject1.put("mobile",mobile);

        JSONObject jsonObject = RestUtil.post("https://qyapi.weixin.qq.com/cgi-bin/user/getuserid?access_token="
                + accessToken ,jsonObject1 );

        Assert.isTrue(jsonObject.getInteger("errcode") == 0, "企业微信手机号获取userid失败:"
                +jsonObject.getString("errmsg"));
        return jsonObject.getString("userid");
    }

    /**
     * 10. 更新用户信息
     * https://qyapi.weixin.qq.com/cgi-bin/user/update?access_token=ACCESS_TOKEN
     */
    public  void updateUser(JSONObject jsonObject) {
        getAccessToken();
        Assert.isTrue(accessToken != null, "企业微信获取access_token失败");
        Assert.isTrue(jsonObject != null, "用户信息不存在");

        JSONObject post = RestUtil.post("https://qyapi.weixin.qq.com/cgi-bin/user/update?access_token="
                + accessToken, jsonObject);
        Assert.isTrue(post.getInteger("errcode") == 0, "企业微信更新用户信息失败:"+post.getString("errmsg"));
    }

    /**
     * 11. 新增成员
     * https://qyapi.weixin.qq.com/cgi-bin/user/create?access_token=ACCESS_TOKEN
     */
    public  void createUser(JSONObject jsonObject) {
        getAccessToken();
        Assert.isTrue(accessToken != null, "企业微信获取access_token失败");
        Assert.isTrue(jsonObject != null, "用户信息不存在");

        JSONObject post = RestUtil.post("https://qyapi.weixin.qq.com/cgi-bin/user/create?access_token="
                + accessToken, jsonObject);
        Assert.isTrue(post.getInteger("errcode") == 0, "企业微信新增成员失败:"+post.getString("errmsg"));
    }

    /**
     * 12. 删除成员
     * https://qyapi.weixin.qq.com/cgi-bin/user/delete?access_token=ACCESS_TOKEN&userid=zhangsan
     */
    public  void deleteUser( String userid) {
        getAccessToken();
        Assert.isTrue(accessToken != null, "企业微信获取access_token失败");
        Assert.isTrue(userid != null, "用户信息不存在");

        JSONObject post = RestUtil.get("https://qyapi.weixin.qq.com/cgi-bin/user/delete?access_token="
                + accessToken + "&userid=" + userid);
        Assert.isTrue(post.getInteger("errcode") == 0, "企业微信删除成员失败:"+post.getString("errmsg"));
    }

    /**
     * 13. 批量删除成员
     * https://qyapi.weixin.qq.com/cgi-bin/user/batchdelete?access_token=ACCESS_TOKEN
     */
    public  void batchDeleteUser(List<String> useridlist ) {
        getAccessToken();
        Assert.isTrue(accessToken != null, "企业微信获取access_token失败");
        Assert.isTrue(! useridlist.isEmpty(), "用户信息不存在");

        JSONObject jsonObject =new JSONObject();
        jsonObject.put("useridlist",useridlist);

        JSONObject post = RestUtil.post("https://qyapi.weixin.qq.com/cgi-bin/user/batchdelete?access_token="
                + accessToken, jsonObject);
        Assert.isTrue(post.getInteger("errcode") == 0, "企业微信批量删除成员失败:"+post.getString("errmsg"));
    }

    /**
     * 14. userid转openid
     * https://qyapi.weixin.qq.com/cgi-bin/user/convert_to_openid?access_token=ACCESS_TOKEN
     */
    public  String convertToOpenid( String userid) {
        getAccessToken();
        Assert.isTrue(accessToken != null, "企业微信获取access_token失败");
        Assert.isTrue(userid != null, "用户信息不存在");

        JSONObject jsonObject1 = new JSONObject();
        jsonObject1.put("userid",userid);

        JSONObject jsonObject = RestUtil.post("https://qyapi.weixin.qq.com/cgi-bin/user/convert_to_openid?access_token="
                + accessToken ,jsonObject1 );

        Assert.isTrue(jsonObject.getInteger("errcode") == 0, "企业微信userid转openid失败:"
                +jsonObject.getString("errmsg"));
        return jsonObject.getString("openid");
    }

    /**
     * 15. openid转userid
     * https://qyapi.weixin.qq.com/cgi-bin/user/convert_to_userid?access_token=ACCESS_TOKEN
     */
    public  String convertToUserid(String openid) {
        getAccessToken();
        Assert.isTrue(accessToken != null, "企业微信获取access_token失败");
        Assert.isTrue(openid != null, "用户信息不存在");

        JSONObject jsonObject1 = new JSONObject();
        jsonObject1.put("openid",openid);

        JSONObject jsonObject = RestUtil.post("https://qyapi.weixin.qq.com/cgi-bin/user/convert_to_userid?access_token="
                + accessToken ,jsonObject1 );

        Assert.isTrue(jsonObject.getInteger("errcode") == 0, "企业微信openid转userid失败:"
                +jsonObject.getString("errmsg"));
        return jsonObject.getString("userid");
    }





}


